﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Input;
using System.Windows.Threading;
using Rabbit.BusinessLogicLayer;
using Rabbit.Model;
using Rabbit.Utils;
using System.Windows;

namespace MicroBlogClient
{
    /// <summary>
    /// Interaction logic for MetionedMe.xaml
    /// </summary>
    public partial class MetionedMe : PageBase
    {
        ObservableCollection<Status> MessagesCollection = new ObservableCollection<Status>();
        List<Status> MessagesPool = new List<Status>();

        MetionedMeStatusBL metionedMeStatusBL;
        public MetionedMe()
        {
            InitializeComponent();

            lstMetionedMeStatusList.ItemsSource = MessagesCollection;

            metionedMeStatusBL = new MetionedMeStatusBL(MySettings.UpdateInterval.Value);
            metionedMeStatusBL.MainMessageList = MessagesCollection;

            metionedMeStatusBL.OnUnknownExceptionOccured = base.OnUnHandledExceptionOccured;
            metionedMeStatusBL.OnMessageInitialized = MessageInitialized;
            metionedMeStatusBL.OnPublishAPICallTooFrequent = base.OnCallAPITooFrequentExceptionOccured;
            metionedMeStatusBL.OnNewMessageReceived = NewMessageReceived;
            BeginInitializeMessage();
        }
       
        void MessageInitialized(List<Status> messageList)
        {
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                messageList.ForEach(message => MessagesCollection.Add(message));
            }), DispatcherPriority.Background); 
        }

        void NewMessageReceived(List<Status> messageList)
        {
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                if (messageList.Count==0)
                {
                    return;
                }

                MessagesCollection.ForEach(s => s.CreatedAt = s.CreatedAt);//refresh the create time on UI 
                MessagesPool.InsertRange(0,messageList);//move new message list to the pool

                TryPopupMessage<Status>(MySettings.PopupForMetionedMe, new Action<object, MouseButtonEventArgs>((o, args) =>
                    {
                        this.Dispatcher.BeginInvoke((Action)delegate()
                        {
                            (App.Current.MainWindow as MainWindow).FlushMetionedMeStatusPool(o, args);
                        });
                    }),
                    MessagesPool.Count,
                    "提到我",
                    messageList[0]
                         );
            }), DispatcherPriority.Background);
        }

        protected override void NotifyMainWindowNewMessageCountChanged(int messageCount)
        {
            (App.Current.MainWindow as MainWindow).NewMetionedMeCount = messageCount;
        }

        public override void DoWork(object obj = null)
        {
            App.StopTwinkleSysTrayIcon();

            MessagesCollection.InsertRange<Status>(MessagesPool, MaxRecordsCountShowed);
            lstMetionedMeStatusList.ScrollIntoView(MessagesCollection[0]);
            MessagesPool.Clear();
            NotifyMainWindowNewMessageCountChanged(0);
        }

        public override void BeginInitializeMessage()
        {
            //base.ShowProcessingMessage("正在获取...");
            metionedMeStatusBL.StartFetchingMessage();
        }

        public override void pager_OnFirstPageClick(object sender, RoutedEventArgs e)
        {
            ShowProcessingMessage("正在加载...");
            Action fetching = () =>
            {
                try
                {
                    List<Status> fetchedMessage = metionedMeStatusBL.GetFirstPageMessage();
                    this.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        MessagesCollection.Clear();
                        fetchedMessage.ForEach(c => MessagesCollection.Add(c));
                        pager.CanPreviousePageClick = false;
                        pager.CanNextPageClick = fetchedMessage.Count > 0;
                    }));
                    ShowSuccessfulMessage("加载完成");
                }
                catch (Exception ex)
                {
                    ShowFailedMessage("获取失败:" + ex.Message);
                }
            };

            fetching.BeginInvoke(null, null);
        }

        public override void pager_OnPreviousePage(object sender, RoutedEventArgs e)
        {
            ShowProcessingMessage("正在加载...");
            Action fetching = () =>
            {
                try
                {
                    List<Status> fetchedMessage = metionedMeStatusBL.GetPreviousePageMessage();
                    this.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        MessagesCollection.Clear();
                        fetchedMessage.ForEach(c => MessagesCollection.Add(c));
                        pager.CanPreviousePageClick = metionedMeStatusBL.CanGetPreviousePage;
                        pager.CanNextPageClick = fetchedMessage.Count > 0;
                    }));
                    ShowSuccessfulMessage("加载完成");
                }
                catch (Exception ex)
                {
                    ShowFailedMessage("获取失败:" + ex.Message);
                }
            };

            fetching.BeginInvoke(null, null);
        }

        public override void pager_OnNextPageClick(object sender, RoutedEventArgs e)
        {
            ShowProcessingMessage("正在加载...");
            Action fetching = () =>
            {
                try
                {
                    List<Status> fetchedMessage = metionedMeStatusBL.GetNextPageMessage();
                    this.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        MessagesCollection.Clear();
                        fetchedMessage.ForEach(c => MessagesCollection.Add(c));
                        pager.CanPreviousePageClick = true;
                        pager.CanNextPageClick = fetchedMessage.Count > 0;
                    }));
                    ShowSuccessfulMessage("加载完成");
                }
                catch (Exception ex)
                {
                    ShowFailedMessage("获取失败:" + ex.Message);
                }
            };

            fetching.BeginInvoke(null, null);
        }
    }
}
